package com.rabbitMq.producer.service;


import com.google.gson.Gson;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class RabbitMqSendService {

    private final RabbitTemplate rabbitTemplate; //使用RabbitTemplate,这提供了接收/发送等等方法
    private final Gson gson = new Gson();

    private final Map<String, Object> okMap = new HashMap<String, Object>() {{
        put("success", true);
    }};
    private final Map<String, Object> noMap = new HashMap<String, Object>() {{
        put("success", false);
    }};

    @Autowired
    public RabbitMqSendService(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    /**
     * 发送消息
     */
    public Map<String, Object> sendMessage(String exchangeName, String routingKey, Map<String, Object> msgMap) {
        try {
            rabbitTemplate.convertAndSend(exchangeName, routingKey, gson.toJson(msgMap));
            return okMap;
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("发送ActiveMq消息失败:" + e.getMessage());
            noMap.put("message", e.getMessage());
            return noMap;
        }
    }

}
